<template>
  <el-dialog
    class="dialog-addsample-list"
    v-model="dialogVisible"
    v-if="load"
    title="选择商品"
    width="1200"
    :close-on-click-modal="false"
    @close="handleClose"
    :z-index="2000"
  >
    <div>
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 8px;
          margin-left: 8px;
        "
      >
        <div class="clearfix">
          <el-input
            v-model.trim="form.sku_cn_title"
            placeholder="产品名称"
            class="fl"
            clearable
            style="width: 208px"
          />
          <el-input
            v-model.trim="form.spu"
            placeholder="SPU"
            class="fl"
            clearable
            style="width: 208px; margin: 0 16px"
          />
          <el-input
            v-model.trim="form.sku"
            placeholder="SKU"
            class="fl"
            clearable
            style="width: 208px; margin: 0 16px"
          />
        </div>
        <el-button type="primary" @click="queryFun"> 查询 </el-button>
      </div>
    </div>
    <vxe-table
      ref="tableRef"
      height="500"
      style="margin-left: 8px"
      @radio-change="radioChangeEvent"
      @checkbox-change="selectChangeEvent"
      @checkbox-all="selectChangeEvent"
      :column-config="{ resizable: true }"
      :row-config="{ isHover: true }"
      :checkbox-config="{ showHeader: true }"
      :data="tableData"
    >
      <vxe-column type="checkbox" width="60" fixed="left"></vxe-column>
      <vxe-column title="产品图片" width="80">
        <template #default="{ row }">
          <VImage
            :width="60"
            :height="60"
            :src="row.attr_img_watermark || row.attr_img"
          />
        </template>
      </vxe-column>
      <vxe-column title="SPU">
        <template #default="{ row }">
          <div>
            <span>{{ row.spu }}</span>
          </div>
        </template>
      </vxe-column>
      <vxe-column title="SKU">
        <template #default="{ row }">
          <div>SKU:{{ row.sku || "--" }}</div>
          <div>自定义:{{ row.custom_sku || "--" }}</div>
        </template>
      </vxe-column>
      <vxe-column title="产品名称" width="250">
        <template #default="{ row }">
          <div>
            <span>{{ row.sku_cn_title }}</span>
          </div>
        </template>
      </vxe-column>
      <vxe-column title="默认供应商">
        <template #default="{ row }">
          <dataAuthority
            auth="supplier_name"
            :value="row.goods_sku_supplier?.supplier_name || '--'"
            :default_value="row.goods_sku_supplier?.supplier_code || '--'"
          ></dataAuthority>
        </template>
      </vxe-column>
      <vxe-column title="采购未税报价">
        <template #default="{ row }">
          <dataAuthority
            auth="unit_price"
            :value="row.supplier_quotation"
          ></dataAuthority>
        </template>
      </vxe-column>
      <vxe-column title="采购未税价">
        <template #default="{ row }">
          <dataAuthority
            auth="purchase_untaxed_price"
            :value="row.purchase_untaxed_price"
          ></dataAuthority>
        </template>
      </vxe-column>
      <vxe-column title="采购含税价">
        <template #default="{ row }">
          <dataAuthority
            auth="unit_price_tax"
            :value="row.unit_price_tax"
          ></dataAuthority>
        </template>
      </vxe-column>
      <vxe-column title="产品状态" width="80">
        <template #default="{ row }">
          <div>
            <span>{{ row.spu_status_text }}</span>
          </div>
        </template>
      </vxe-column>
    </vxe-table>
    <div
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
      "
    >
      <div>
        <vxe-pager
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalResult"
          :page-sizes="[10, 20, 100]"
          @page-change="pageChange"
          :layouts="[
            'PrevJump',
            'PrevPage',
            'Number',
            'NextPage',
            'NextJump',
            'Sizes',
            'FullJump',
            'Total',
          ]"
        >
        </vxe-pager>
      </div>
      <div class="flex items-center">
        <el-checkbox style="margin-right: 8px" v-model="includeSKU"
          >带出SPU所有变体SKU</el-checkbox
        >
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="serveFun"> 保存 </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { querySkuList } from "../api";
import { ref, reactive, onMounted, toRaw } from "vue";
import { ElMessage } from "element-plus";
import VImage from "@/components/Image/index.vue";

const totalResult = ref(1);
const currentPage = ref(1);
const pageSize = ref(20);
const dialogVisible = ref(false);
let tableData = ref([]);
let propsData = ref([]);
const form = reactive({
  spu: "",
  sku_cn_title: "",
});

const data = reactive({
  includeSKU: false,
  load: false,
});

const { includeSKU, load } = toRefs(data);

const props = defineProps({
  list: {
    type: Array,
    default: () => {
      return [];
    },
  },
  supplier_id: {
    type: [Number, String],
  },
});

const { supplier_id } = toRefs(props);

const checked_list = computed(() => {
  return props.list;
});

onMounted(() => {
  initData({
    spu: form.spu,
    sku_cn_title: form.sku_cn_title,
    sku: form.sku,
    only_sku: 1,
    default_supplier_id: 1,
  });
});

const initData = (data = {}) => {
  querySkuList(data).then(({ total, data }) => {
    tableData.value = data;
    totalResult.value = total;
  });
};

const queryFun = () => {
  initData({
    spu: form.spu,
    sku_cn_title: form.sku_cn_title,
    sku: form.sku,
    only_sku: 1,
    default_supplier_id: 1,
  });
};

const open = async (_) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  dialogVisible.value = true;
};

const handleClose = () => {
  includeSKU.value = false;
  dialogVisible.value = false;
};

const pageChange = () => {
  initData({
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    only_sku: 1,
    default_supplier_id: 1,
  });
};

const serveFun = () => {
  if (!propsData.value.length) {
    return ElMessage({
      message: "至少选择一个商品",
      type: "error",
    });
  }
  if (!checkArray(propsData.value)) {
    ElMessage.error("请选择相同供应商");
    return;
  }

  if (includeSKU.value) {
    const spu = [];
    propsData.value.forEach((element) => {
      spu.push(element.spu);
    });

    querySkuList({
      spu: [...new Set(spu)],
      only_sku: 1,
      default_supplier_id: 1,
    }).then((res) => {
      if (!checkArray(res.data)) {
        ElMessage.error("SPU所有变体SKU 供应商需要一致");
        return;
      }
      const product_list = res.data.map((e, idx) => {
        return {
          serial_num: idx,
          spu: e.spu,
          sku: e.sku,
          spu_category: e.spu_category,
          custom_sku: e.custom_sku,
          sku_cn_title: e.sku_cn_title,
          purchase_price: e.supplier_quotation,
          purchase_amount: e.supplier_quotation,
          purchase_quantity: 1,
          attr_img: e.attr_img,
          attr_img_watermark: e.attr_img_watermark,
          supplier_quotation: e.supplier_quotation,
          purchase_untaxed_price: e.purchase_untaxed_price,
          unit_price_tax: e.unit_price_tax,
          supplier_id: e.goods_sku_supplier?.supplier_id,
          purchaser_id: e.purchaser_id,
          goods_sku_supplier: e.goods_sku_supplier,
        };
      });
      const checkResult = checkSupplierAndSkuUniqueness(
        checked_list.value,
        product_list,
        supplier_id.value
      );
      if (checked_list.value.length && !checkResult.valid) {
        ElMessage.error(checkResult.error);
        return;
      }
      emits("addSampleListQuery", product_list);
      dialogVisible.value = false;
    });
  } else {
    const checkResult = checkSupplierAndSkuUniqueness(
      checked_list.value,
      propsData.value,
      supplier_id.value
    );
    if (checked_list.value.length && !checkResult.valid) {
      ElMessage.error(checkResult.error);
      return;
    }
    console.log(propsData.value);
    emits("addSampleListQuery", reactive(propsData.value));
    dialogVisible.value = false;
  }
};

const checkArray = (arr) => {
  // 检查数组长度是否大于0
  if (arr.length === 0) {
    return false;
  }
  // 获取第一个非零元素作为默认值
  let defaultSupplierId = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].goods_sku_supplier?.supplier_id !== 0) {
      defaultSupplierId = arr[i].goods_sku_supplier?.supplier_id;
      break;
    }
  }

  // 检查数组中的元素是否都与默认值相同且不为0
  for (let i = 0; i < arr.length; i++) {
    if (
      arr[i].goods_sku_supplier?.supplier_id !== defaultSupplierId ||
      arr[i].goods_sku_supplier?.supplier_id === 0
    ) {
      return false;
    }
  }

  return true;
};

const tableRef = ref();

const radioChangeEvent = ({ $table }) => {
  const records = $table.getRadioRecord();
  propsData.value = JSON.parse(JSON.stringify(records));
};

const selectChangeEvent = ({ $table }) => {
  const records = $table.getCheckboxRecords();
  propsData.value = JSON.parse(JSON.stringify(records));
};

const clearSelectEvent = () => {
  const $table = tableRef.value;
  if ($table) {
    $table.clearCheckboxRow();
  }
};

const emits = defineEmits("addSampleListQuery");
defineExpose({ open, clearSelectEvent });

const checkSameSupplier = (list, selectedItems) => {
  const supplierIds = list.map((item) => item.supplier_id);
  for (const item of selectedItems) {
    if (!supplierIds.includes(item.goods_sku_supplier?.supplier_id)) {
      return false;
    }
  }
  return true;
};

const checkSupplierAndSkuUniqueness = (list, selectedItems, supplier_id) => {
  // 检查供应商ID一致性
  const listSupplierIds = new Set(
    selectedItems.map((item) => item.goods_sku_supplier?.supplier_id)
  );
  if (!listSupplierIds.has(supplier_id)) {
    return { error: "选择的商品供应商与列表中的供应商不一致", valid: false };
  }

  const skusSet = new Set(
    list.map((item) => (item.goods_sku ? item.goods_sku : item.sku))
  );
  const selectedSkusSet = new Set(selectedItems.map((item) => item.sku));

  for (const sku of selectedSkusSet) {
    if (skusSet.has(sku)) {
      return { error: "选择的SKU或者带出的变体与选中的商品存在重复", valid: false }; // 发现重复的sku
    }
  }
  return { error: null, valid: true };
};
</script>
<style lang="scss">
.dialog-addsample-list {
  .el-dialog__body {
    padding-bottom: 10px !important;
  }
}
</style>
